package com.hoangkien.activity;

import com.hoangkien.entity.CategoryEntity;
import com.hoangkien.entity.ImageEntity;
import com.hoangkien.service.CategoryService;
import com.hoangkien.service.ImageService;
import com.mango.hoangkien.coloringkids.R;
import com.mango.hoangkien.coloringkids.R.layout;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;

public class HomekidsActivity extends Activity {
	
	Button mStarter;
	Button drawButton;
    ViewGroup mContainer;
    private static final AccelerateInterpolator sAccelerator = new AccelerateInterpolator();
    private static final DecelerateInterpolator sDecelerator = new DecelerateInterpolator();
    private static final LinearInterpolator sLinearInterpolator = new LinearInterpolator();
    static long SHORT_DURATION = 100;
    static long LONG_DURATION = 500;
    
    @SuppressLint("NewApi") 
    private static float sDurationScale = 1f;
    private Button btUp;
    
    public static void actionLaunch(Context context) {
    	Intent intent = new Intent(context,HomekidsActivity.class);
    	context.startActivity(intent);
	}

	@SuppressLint("NewApi") @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.home_layout);
		
		mContainer = (ViewGroup) findViewById(R.id.container);
		
		mStarter = (Button) findViewById(R.id.startButton);
        mStarter.setOnTouchListener(funButtonListener);
        mStarter.animate().setDuration(100);
        drawButton = (Button) findViewById(R.id.drawButton);
        drawButton.setOnTouchListener(funButtonListener);
        drawButton.animate().setDuration(100);
        
        btUp = (Button) findViewById(R.id.up);
        btUp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Intent intent = new Intent(HomekidsActivity.this, ImageByCategoryActivity.class);
//				startActivity(intent);
			}
		});
        
        testDB();
	}
	
	@SuppressLint("NewApi") @Override
    protected void onResume() {
        super.onResume();
        mContainer.setScaleX(1);
        mContainer.setScaleY(1);
        mContainer.setAlpha(1);
        mStarter.setVisibility(View.INVISIBLE);
        drawButton.setVisibility(View.INVISIBLE);
        mContainer.getViewTreeObserver().addOnPreDrawListener(mOnPreDrawListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mStarter.removeCallbacks(mSquishRunnable);
        drawButton.removeCallbacks(mSquishRunnable);
    }

    private OnTouchListener funButtonListener = new OnTouchListener() {
        @SuppressLint("NewApi") @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            	if(v.getId() == R.id.startButton){
            		 mStarter.animate().scaleX(.8f).scaleY(.8f).setInterpolator(sDecelerator);
                     mStarter.setTextColor(Color.CYAN);
                     mStarter.removeCallbacks(mSquishRunnable);
                     mStarter.setPressed(true);
            	}
            	if(v.getId() == R.id.drawButton){
            		drawButton.animate().scaleX(.8f).scaleX(.8f).setInterpolator(sDecelerator);
                    drawButton.setTextColor(Color.CYAN);
                    drawButton.removeCallbacks(mSquishRunnable);
                    drawButton.setPressed(true);
            	}
                
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();
                if(v.getId() == R.id.startButton){
                	 boolean isInside = (x > 0 && x < mStarter.getWidth() && y > 0 && y < mStarter.getHeight());
                     if (mStarter.isPressed() != isInside) {
                         mStarter.setPressed(isInside);
                     }
                }
                if(v.getId() == R.id.drawButton){
                	boolean isInside = (x > 0 && x < drawButton.getWidth() && y > 0 && y < drawButton.getHeight());
                	if (drawButton.isPressed() != isInside) {
                    	drawButton.setPressed(isInside);
                    }
                }
                
                break;
            case MotionEvent.ACTION_UP:
            	if(v.getId() == R.id.startButton){
            		if (mStarter.isPressed()) {
                        mStarter.performClick();
                        mStarter.setPressed(false);
                    } else {
                        mStarter.animate().scaleX(1).scaleY(1).setInterpolator(sAccelerator);
                    }
                    mStarter.setTextColor(Color.BLUE);
            	}
            	if(v.getId() == R.id.drawButton){
            		if (drawButton.isPressed()) {
                    	drawButton.performClick();
                    	drawButton.setPressed(false);
                    } else {
                    	drawButton.animate().scaleX(1).scaleY(1).setInterpolator(sAccelerator);
                    }
                    drawButton.setTextColor(Color.BLUE);
            	}
                break;
            }
            return true;
        }
    };
    
    private Runnable mSquishRunnable = new Runnable() {
        public void run() {
//            squishyBounce(mStarter, 0,mContainer.getHeight() - mStarter.getTop() - mStarter.getHeight(),0, .5f, 1.5f);
        }
    };
    
    @SuppressLint("NewApi") 
    public void play(View view) {
        mStarter.animate().scaleX(5).scaleY(5).alpha(0).setDuration(LONG_DURATION).setInterpolator(sLinearInterpolator).withEndAction(new Runnable() {
            @Override
            public void run() {
                mStarter.postOnAnimation(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(HomekidsActivity.this, ColoringBitmapActivity.class);
                        startActivity(intent);
                        overridePendingTransition(0, 0);
                    }
                });
            }
        });
        view.removeCallbacks(mSquishRunnable);
    }
    @SuppressLint("NewApi") 
    public void draw(View view) {
    	drawButton.animate().scaleX(5).scaleY(5).alpha(0).setDuration(LONG_DURATION).setInterpolator(sLinearInterpolator).withEndAction(new Runnable() {
    		@Override
    		public void run() {
    			drawButton.postOnAnimation(new Runnable() {
    				public void run() {
    					Intent intent = new Intent(HomekidsActivity.this, DrawBitmapActivity.class);
    					startActivity(intent);
    					overridePendingTransition(0, 0);
    				}
    			});
    		}
    	});
    	view.removeCallbacks(mSquishRunnable);
    }
    
    private ViewTreeObserver.OnPreDrawListener mOnPreDrawListener = new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            mContainer.getViewTreeObserver().removeOnPreDrawListener(this);
            mContainer.postDelayed(new Runnable() {
                @SuppressLint("NewApi") 
                public void run() {
                    mStarter.setVisibility(View.VISIBLE);
                    mStarter.setY(-mStarter.getHeight());
                    squishyBounce(mStarter, -(mStarter.getTop() + mStarter.getHeight()), mContainer.getHeight() - mStarter.getTop() - mStarter.getHeight(),0, .5f, 1.5f);
                    drawButton.setVisibility(View.VISIBLE);
                    drawButton.setY(-drawButton.getHeight());
                    squishyBounce(drawButton, -(drawButton.getTop() + drawButton.getHeight()), mContainer.getHeight() - drawButton.getTop() - drawButton.getHeight(),0, .5f, 1.5f);
                }
            }, 500);
            return true;
        }
    };

    @SuppressLint("NewApi") 
    private void squishyBounce(final View view, final float startTY, final float bottomTY,  final float endTY, final float squash, final float stretch) {
        view.setPivotX(view.getWidth() / 2);
        view.setPivotY(view.getHeight());
        PropertyValuesHolder pvhTY = PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, startTY, bottomTY);
        PropertyValuesHolder pvhSX = PropertyValuesHolder.ofFloat(View.SCALE_X, .7f);
        PropertyValuesHolder pvhSY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.2f);
        ObjectAnimator downAnim = ObjectAnimator.ofPropertyValuesHolder(view, pvhTY, pvhSX, pvhSY);
        downAnim.setInterpolator(sAccelerator);

        pvhTY = PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, bottomTY, endTY);
        pvhSX = PropertyValuesHolder.ofFloat(View.SCALE_X, 1);
        pvhSY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1);
        ObjectAnimator upAnim = ObjectAnimator.ofPropertyValuesHolder(view, pvhTY, pvhSX, pvhSY);
        upAnim.setInterpolator(sDecelerator);
        
        pvhSX = PropertyValuesHolder.ofFloat(View.SCALE_X, stretch);
        pvhSY = PropertyValuesHolder.ofFloat(View.SCALE_Y, squash);
        ObjectAnimator stretchAnim = ObjectAnimator.ofPropertyValuesHolder(view, pvhSX, pvhSY);
        stretchAnim.setRepeatCount(1);
        stretchAnim.setRepeatMode(ValueAnimator.REVERSE);
        stretchAnim.setInterpolator(sDecelerator);
        
        AnimatorSet set = new AnimatorSet();
        set.playSequentially(downAnim, stretchAnim, upAnim);
        set.setDuration(getDuration(SHORT_DURATION));
        set.start();
        set.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator animation) {
                view.postDelayed(mSquishRunnable, (long) (500 + Math.random() * 2000));
            }
        });
    }
    
    public static long getDuration(long baseDuration) {
        return (long) (baseDuration * sDurationScale);
    }
    
    private void testDB() {
//    	CategoryEntity categoryEntity = new CategoryEntity(1, "anh nguoi");
//    	CategoryService categoryService = new CategoryService(HomekidsActivity.this);
//    	categoryService.insert_category(categoryEntity);
//    	ImageEntity imageEntity = new ImageEntity(1, 1, "link small", "link_large", "anh anh");
//    	ImageService imageService = new ImageService(HomekidsActivity.this);
//    	imageService.insert_image(imageEntity);
	}
}
